/**
 * 文件选择器模块
 * 处理工作区文件的选择和信息提取
 */

import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import type { Attachment } from '../types/types';

/**
 * 打开文件选择器，让用户从工作区选择文件
 * @returns 选中的文件列表，如果用户取消则返回 undefined
 */
export async function selectFilesFromWorkspace(): Promise<Attachment[] | undefined> {
    try {
        // 获取工作区所有文件
        const workspaceFiles = await vscode.workspace.findFiles(
            '**/*',              // 匹配所有文件
            '**/node_modules/**' // 排除 node_modules
        );

        if (workspaceFiles.length === 0) {
            vscode.window.showInformationMessage('工作区中没有找到文件');
            return undefined;
        }

        // 获取工作区根路径
        const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
        const workspaceRoot = workspaceFolder?.uri.fsPath;

        // 准备 QuickPick 选项
        const fileItems = workspaceFiles.map(uri => {
            const filePath = uri.fsPath;
            const relativePath = workspaceRoot 
                ? path.relative(workspaceRoot, filePath)
                : filePath;
            
            return {
                label: path.basename(filePath),
                description: relativePath,
                uri: uri
            };
        });

        // 显示文件选择器
        const selectedItems = await vscode.window.showQuickPick(fileItems, {
            canPickMany: true,
            placeHolder: '选择要添加到对话的文件（可多选）',
            matchOnDescription: true  // 支持按路径搜索
        });

        if (!selectedItems || selectedItems.length === 0) {
            // 用户取消选择
            return undefined;
        }

        // 转换为 Attachment 对象
        const attachments: Attachment[] = selectedItems.map(item => {
            const filePath = item.uri.fsPath;
            const fileName = path.basename(filePath);
            const language = getLanguageFromPath(filePath);
            
            // 计算相对路径
            let relativePath: string | undefined;
            if (workspaceRoot && filePath.startsWith(workspaceRoot)) {
                relativePath = path.relative(workspaceRoot, filePath);
            }

            // 获取文件大小
            let size: number | undefined;
            try {
                const stats = fs.statSync(filePath);
                size = stats.size;
            } catch (error) {
                // 忽略获取大小失败的情况
            }

            return {
                type: 'file',
                path: filePath,
                name: fileName,
                relativePath,
                language,
                size
            };
        });

        return attachments;

    } catch (error) {
        vscode.window.showErrorMessage(`选择文件失败: ${error}`);
        console.error('File selection error:', error);
        return undefined;
    }
}

/**
 * 根据文件路径推断语言类型
 */
export function getLanguageFromPath(filePath: string): string | undefined {
    const ext = path.extname(filePath).toLowerCase();
    const languageMap: Record<string, string> = {
        '.ts': 'typescript',
        '.js': 'javascript',
        '.jsx': 'javascriptreact',
        '.tsx': 'typescriptreact',
        '.py': 'python',
        '.java': 'java',
        '.cpp': 'cpp',
        '.c': 'c',
        '.cs': 'csharp',
        '.go': 'go',
        '.rs': 'rust',
        '.rb': 'ruby',
        '.php': 'php',
        '.html': 'html',
        '.css': 'css',
        '.scss': 'scss',
        '.json': 'json',
        '.xml': 'xml',
        '.yaml': 'yaml',
        '.yml': 'yaml',
        '.md': 'markdown',
        '.sh': 'shell',
        '.bash': 'shell',
        '.sql': 'sql'
    };
    return languageMap[ext];
}
